package com.example.demo.controller;


import com.example.demo.entity.CodeMsg;
import com.example.demo.entity.Email;
import com.example.demo.entity.userAdd;
import com.example.demo.model.MD5Util;
import com.example.demo.model.result;
import com.example.demo.services.MailService;
import com.example.demo.services.userIdAdService;
import com.example.demo.services.userLoginServices;
import com.example.demo.services.userSecServices;
import com.example.demo.utils.RedisUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.xml.transform.Templates;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
@RequestMapping("/add")
public class userSecAddController {


    @Autowired
    private userSecServices userSecServices;

    @Autowired
    private userIdAdService userIdAdService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private userLoginServices userLoginServices;

    @Autowired
    private MailService mailService;


    @PostMapping("/sendEmail")
    public result sendEmail(String emailName,String loginName){
        Email email=new Email();
        List<String> emailUrl=new ArrayList<String>();
        emailUrl.add(emailName);
        email.setToAddress(emailUrl);
        email.setSubject("注册验证码");
        /*
        验证码注册，设置验证码过期时间 2分钟前端设置 1分钟 放到redis里面去,邮件发送大概是2秒中时间
         */
        String test= String.format("%04d",new Random().nextInt(9999));
        email.setContent("您好<br><br> 用户验证码为:"+test);
        mailService.sendMail(email);
        boolean pduan= redisUtil.set(loginName,test,180);
        if(pduan==false){
            return result.fail(CodeMsg.EMAIL_HAVING);
        }
        return result.success("ok");
    }


    @PostMapping("/userSec")
    public result userSec(@RequestBody userAdd useradd, @RequestParam String code, @Param("email")String email) throws InterruptedException {
        //下面是服务器自动设置不重复id长度为16位
        StringBuilder userId=new StringBuilder();
        //前8位为时间信息
        LocalDateTime now=LocalDateTime.now();
        String nowDate=now.format(DateTimeFormatter.ISO_DATE).replace("-","");
        userId.append(nowDate);

        //中间6位为自增序列
        int sequence=0;
        int id=userIdAdService.selectTabel("user_login").getUserid();
        int add=userIdAdService.selectTabel("user_login").getSec();
        int h=id+add;
        userIdAdService.upuserId(h,"user_login");
        String s=String.valueOf(h);
        for (int i = 0; i <6-s.length() ; i++) {
            userId.append(0);
        }
        userId.append(s);

        //最后两位数为分库分表位
        userId.append("00");
        //加密密码插入mysql
        String test_password= MD5Util.inputpass(useradd.getPassword(),"1a2b3c");
        if(!redisUtil.hasKey(useradd.getLoginName())){
            return result.fail("用户还未发送验证码请求");
        }
        //下面开始为验证码登录，验证码通过后才会向数据库添加数据
        //取redis中的普通缓存的值的话  类型是 object 要将其强转成 String 然后用equals判断 不然数据不对应 返回错误 无法跳出 循环体
        String hello= (String) redisUtil.get(useradd.getLoginName());
        int n=0;
        //定时 2分钟 验证码等待 可以多次请求 不能多次发送 我上面有 限制 用redis判断 重复键值 重复就跳出错误 返回异常
        for (int i = 0; i <120 ; i++) {
            Thread.sleep(1000);
            n++;
            if(hello.equals(code)){
                break;
            }else {
                return result.fail("验证码错误");
            }
        }
        if(n==120){
            return result.fail("验证码超时了");
        }
        //双表加入数据
        int test1=userLoginServices.adduser(userId.toString(),useradd.getName(),useradd.getLoginName(),test_password);
        int test=userSecServices.adduserSec(userId.toString(),useradd.getLifeCity(),useradd.getAge(),useradd.getTelephone(),useradd.getCreateTime(),useradd.getTeacher(),useradd.getTeacherId());
        if(test==1){

            Email emailTest=new Email();
            List<String> emailUrl=new ArrayList<String>();
            emailUrl.add(email);
            emailTest.setToAddress(emailUrl);
            emailTest.setSubject("您的注册学号");
            emailTest.setContent(userId.toString());
            mailService.sendMail(emailTest);
            return result.success(test);
        }else {
            return result.fail(test);
        }
    }

}
